package config

import (
	"fmt"
	"io/ioutil"

	"gopkg.in/yaml.v2"
)

type TemplateCfg struct {
	TemplateId  uint64 `yaml:"templateId"`
	AuthCodeKey string `yaml:"authCodeKey"`
	Title       string `yaml:"title"`
}

func (cfg *TemplateCfg) check(prefix string) error {
	if cfg.TemplateId == 0 {
		return fmt.Errorf("miss %s.templateId config", prefix)
	}
	if cfg.AuthCodeKey == "" {
		return fmt.Errorf("miss %s.authCodeKey config", prefix)
	}
	if cfg.Title == "" {
		return fmt.Errorf("miss %s.title config", prefix)
	}
	return nil
}

type ServerConfig struct {
	ListenAddr string      `yaml:"listenAddr"`
	Region     string      `yaml:"region"`
	SendUser   string      `yaml:"sendUser"`
	SecretId   string      `yaml:"secretId"`
	SecretKey  string      `yaml:"secretKey"`
	RegMail    TemplateCfg `yaml:"regMail"`
	ResetMail  TemplateCfg `yaml:"resetMail"`
}

func ReadConfig(fileName string) (*ServerConfig, error) {
	data, err := ioutil.ReadFile(fileName)
	if err != nil {
		return nil, err
	}
	servCfg := &ServerConfig{}
	err = yaml.Unmarshal(data, servCfg)
	if err != nil {
		return nil, err
	}
	if servCfg.Region == "" {
		return nil, fmt.Errorf("miss region config")
	}
	if servCfg.SendUser == "" {
		return nil, fmt.Errorf("miss sendUser config")
	}
	if servCfg.SecretId == "" {
		return nil, fmt.Errorf("miss secretId config")
	}
	if servCfg.SecretKey == "" {
		return nil, fmt.Errorf("miss secretKey config")
	}
	err = servCfg.RegMail.check("regMail")
	if err != nil {
		return nil, err
	}
	err = servCfg.ResetMail.check("resetMail")
	if err != nil {
		return nil, err
	}
	return servCfg, nil
}
